<script setup lang="ts">
import { requiredCheck } from "@/utils/verify";
import { ref } from "vue";
import { addData, editData } from "@/api/modules/system/account";

interface Props {
  title?: string;
  rowData?: Object;
}

const props = withDefaults(defineProps<Props>(), {
  title: "新增账号",
  rowData: undefined
});
defineOptions({
  name: "UpdateForm" // 默认策略
});
import useUpdate from "@/hooks/useUpdate";
import { ifaceAll, ifacemodeUpdate } from "@/api/modules/dynamic-camouflage/line-config";
import { cfgPamGet } from "@/api/modules/system/params";

const emits = defineEmits(["success"]);
const { updateFormData, updateFormRef, updateFormRules, submit, showHandle, openHandle, closeHandle } = useUpdate({
  rules: {
    name: [...requiredCheck("请输入用户名")],
    password: [
      ...requiredCheck("请输入密码"),
      {
        validator: (rule, value, callback) => {
          const checkPasswordRules = passwordPwd.value;
          const getTip = () => {
            let str = "密码长度至少" + Number(checkPasswordRules.min_length) + "位";
            let isLetterAndNumber = false;
            let isLetterSpecialChar = false;
            if (Number(checkPasswordRules.char_number)) {
              isLetterAndNumber = true;
              str += `且包含字母和数字`;
            }
            if (Number(checkPasswordRules.upper_lower)) {
              isLetterSpecialChar = true;
              if (isLetterAndNumber) {
                str += `、大小写混合`;
              } else {
                str += `且包含大小写混合`;
              }
            }
            if (Number(checkPasswordRules.special_char)) {
              if (isLetterSpecialChar || isLetterAndNumber) {
                str += `和特殊字符`;
              } else {
                str += `且包含特殊字符`;
              }
            }
            return str;
          };
          const tipMsg = getTip();
          // 密码需要字母和数字
          const letterAndNumber = /^(?=.*[a-zA-Z])(?=.*\d).+$/;
          // 包含特殊字符
          const specialCharacter = /[!@#$%^&*\/(),.?":{}|<>]/;
          // 大小写混合
          const mixedCase = /^(?=.*[a-z])(?=.*[A-Z]).+$/;
          // 判断密码最小长度
          if (value.length < Number(checkPasswordRules.min_length)) {
            callback(new Error(tipMsg));
          }
          // 是否字母加数字
          if (Number(checkPasswordRules.char_number)) {
            // showPasswordDialog
            if (!letterAndNumber.test(value)) {
              callback(new Error(tipMsg));
            }
          }
          // 是否特殊字符
          if (Number(checkPasswordRules.special_char)) {
            if (!specialCharacter.test(value)) {
              callback(new Error(tipMsg));
            }
          }
          // 是否大小写混合
          if (Number(checkPasswordRules.upper_lower)) {
            if (!mixedCase.test(value)) {
              callback(new Error(tipMsg));
            }
          }
          callback();
        }
      }
    ],
    passwordRe: [
      {
        validator: (rule, value, callback) => {
          if (value !== updateFormData.password) {
            callback(new Error("两次输入的密码不一致"));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ]
  },
  defaultData: {
    role: "1"
  }
});
const ifaces = ref([]);
const passwordPwd = ref({});

async function getCfg() {
  const res = await cfgPamGet();
  console.log("res", res);
  passwordPwd.value = res;
}

async function getIface() {
  try {
    const res = await ifaceAll();
    console.log(res);
    if (res) {
      ifaces.value = Object.values(res);
      console.log(ifaces.value);
    }
    Object.values(res);
  } catch (error) {}
}

async function submitCb() {
  await submit({
    addApi: addData,
    updateApi: editData,
    sendData: {
      name: updateFormData.name,
      passwordRe: updateFormData.passwordRe || "",
      password: updateFormData.password || "",
      role: updateFormData.role,
      id: updateFormData?.id
    }
  });
  emits("success");
}
</script>

<template>
  <div
    class="update-form mg-r-sm"
    style="display: inline-block"
    @click="
      openHandle({
        row: {
          ...rowData
        },
        id: props.rowData?.id
      });

      getIface();
      getCfg();
    "
  >
    <slot>
      <el-button type="primary">新增</el-button>
    </slot>
  </div>
  <base-dialog @confirm="submitCb()" width="500px" :title="title" v-model="showHandle">
    <div class="details">
      <div class="details-main">
        <el-form ref="updateFormRef" :model="updateFormData" :rules="updateFormRules" label-width="120px" label-suffix="：">
          <el-form-item label="用户名" prop="name">
            <el-input
              style="width: 240px"
              v-model.trim="updateFormData.name"
              placeholder="请输入用户名"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="角色" prop="role">
            <el-select v-model="updateFormData.role" style="width: 240px">
              <el-option label="系统管理员" :value="'1'" />
              <el-option label="安全管理员" :value="'2'" />
              <el-option label="审计管理员" :value="'3'" />
            </el-select>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              style="width: 240px"
              v-model="updateFormData.password"
              type="password"
              show-password
              auto-complete="off"
              placeholder="请输入用户密码"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="passwordRe">
            <el-input
              style="width: 240px"
              v-model="updateFormData.passwordRe"
              auto-complete="off"
              show-password
              type="password"
              placeholder="请再次输入用户密码"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <template #footer-more-button></template>
  </base-dialog>
</template>

<style lang="scss" scoped></style>
